package com.luo.controller;

import com.alibaba.fastjson.JSON;
import com.luo.model.ResultObj;
import com.luo.model.User;
import com.luo.service.UserService;
import com.luo.util.RedisUtil;
import com.luo.util.UsersMap;
import redis.clients.jedis.Jedis;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Objects;

/**
 * 功能：
 * 作者：Luo。
 * 日期：2024/1/24 20:28
 */
@WebServlet("/LoginBool")
public class LoginBoolController extends HttpServlet {

    UserService userService = new UserService();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ResultObj resultObj = new ResultObj();
        // 获取前端token
        String token = req.getParameter("Authorization");
        token = token.substring(token.indexOf(" ") + 1);
        Jedis jedis = RedisUtil.getJedis();
        // 根据token获取数据库中的值
        String tokenRedis = jedis.hget(token, "token");
        String username = jedis.hget(token, "username");
        String id = jedis.hget(token, "id");
        //判断数据库用户是否存在
        if (id == null || username == null){
            resultObj.setCode("-1");
            resultObj.setMsg("用户未登录或登录已过期");
            String jsonString = JSON.toJSONString(resultObj);
            resp.getWriter().write(jsonString);
            resp.getWriter().close();
        }
        //redis数据库中存在用户
        //根据用户id到数据库查询用户详细信息
        User user = userService.queryUserById(id);
        resultObj.setCode("1");
        resultObj.setMsg("用户登录有效");
        resultObj.setResult(user);
        String jsonString = JSON.toJSONString(resultObj);
        resp.getWriter().write(jsonString);
        resp.getWriter().close();
    }
}
